<template>
  <div class="visit-appointment">
    <!-- 搜索筛选区 -->
    <div class="query-section">
      <el-card shadow="hover" class="query-card">
        <template #header>
          <div class="card-header-title">
            <el-icon><Search /></el-icon>
            <span>搜索条件</span>
          </div>
        </template>
        <el-form :model="queryParams" ref="queryFormRef" label-width="80px" class="query-grid">
          <el-row :gutter="24">
            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="姓名" prop="name">
                <el-input v-model.trim="queryParams.name" placeholder="请输入姓名" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model.trim="queryParams.mobile" placeholder="请输入手机号" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="老人" prop="elderName">
                <el-input v-model.trim="queryParams.elderName" placeholder="请输入老人姓名" clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                  <el-option label="全部" value="" />
                  <el-option label="待确定" :value="0" />
                  <el-option label="待完成" :value="1" />
                  <el-option label="取消" :value="2" />
                  <el-option label="过期" :value="3" />
                  <el-option label="完成" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :offset-md="16" :xs-offset="0">
              <el-form-item label-width="0" class="query-buttons">
                <el-button type="primary" @click="handleQuery" :loading="loading" icon="Search">查询</el-button>
                <el-button @click="resetQuery" icon="Refresh">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>

    <!-- 操作栏 -->
    <div class="action-section">
      <el-card shadow="never" class="action-card">
        <div class="action-bar">
          <div class="action-left">
            <el-button type="info" icon="Refresh" @click="handleRefresh" :loading="loading">刷新</el-button>
            <el-button type="success" icon="Plus" @click="openAddDialog">新增探访预约</el-button>
            <el-button type="danger" icon="Delete" @click="handleBatchDelete" :disabled="!selectedRows.length">批量删除</el-button>
          </div>
          <div class="total-info">共 <strong class="total-count">{{ totalItems }}</strong> 条记录</div>
        </div>
      </el-card>
    </div>

    <!-- 内容区 -->
    <div class="content-section">
      <el-card shadow="never" class="content-card">
        <!-- 桌面端表格 -->
        <div v-if="isDesktop" class="desktop-table">
          <el-table :data="tableData" border stripe v-loading="loading" v-model:selection="selectedRows" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="姓名" prop="name" align="center" />
            <el-table-column label="手机号" prop="mobile" align="center" />
            <el-table-column label="老人姓名" prop="elderName" align="center" />
            <el-table-column label="探访时间" prop="time" align="center" />
            <el-table-column label="随行人数" prop="numberOfPeople" align="center" />
            <el-table-column label="状态" prop="status" align="center">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)" effect="light">{{ statusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160">
              <template #default="{ row }">
                <div class="table-actions">
                  <el-tooltip v-if="row.status === 0" content="审核通过" placement="top">
                    <el-button circle type="success" size="small" @click="approveVisit(row.id)">
                      <el-icon><Check /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="取消预约" placement="top">
                    <el-button circle type="warning" size="small" @click="cancelVisit(row.id)">
                      <el-icon><CircleClose /></el-icon>
                    </el-button>
                  </el-tooltip>

                  <el-tooltip content="删除" placement="top">
                    <el-button circle type="danger" size="small" @click="deleteRow(row.id)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 移动端卡片 -->
        <div v-else class="mobile-list">
          <el-empty v-if="!tableData.length && !loading" description="暂无探访预约" />
          <div v-for="item in tableData" :key="item.id" class="mobile-card">
            <el-checkbox v-model="selectedRows" :label="item" class="mobile-checkbox">
              <span class="sr-only">选择</span>
            </el-checkbox>
            <div class="card-main">
              <div class="card-header">
                <div class="left">
                  <span class="name">{{ item.name }}</span>
                  <span class="mobile">{{ item.mobile }}</span>
                </div>
                <el-tag :type="statusTagType(item.status)" effect="dark" round>
                  {{ statusText(item.status) }}
                </el-tag>
              </div>
              <div class="card-info">
                <div class="info-item">
                  <span class="label">老人姓名</span>
                  <span class="value">{{ item.elderName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">探访时间</span>
                  <span class="value">{{ item.time }}</span>
                </div>
                <div class="info-item">
                  <span class="label">随行人数</span>
                  <span class="value">{{ item.numberOfPeople }} 人</span>
                </div>
              </div>
              <div class="card-actions">
                <el-button
                  v-if="item.status === 0"
                  size="small"
                  type="success"
                  plain
                  @click="approveVisit(item.id)"
                >
                  <el-icon><Check /></el-icon> 审核
                </el-button>
                <el-button
                  size="small"
                  type="warning"
                  plain
                  @click="cancelVisit(item.id)"
                >
                  <el-icon><CircleClose /></el-icon> 取消
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  plain
                  @click="deleteRow(item.id)"
                >
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="totalItems"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增抽屉 -->
    <el-drawer
      v-model="addDrawerVisible"
      title="新增探访预约"
      direction="rtl"
      size="420"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100"
        label-position="right"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input-number v-model="addForm.userId" :min="1" style="width:100%" />
        </el-form-item>
        <el-form-item label="预约人姓名" prop="name">
          <el-input v-model="addForm.name" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile" maxlength="11" />
        </el-form-item>
        <el-form-item label="预约时间" prop="time">
          <el-date-picker
            v-model="addForm.time"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="随行人数" prop="numberOfPeople">
          <el-input-number v-model="addForm.numberOfPeople" :min="1" :max="20" style="width:100%" />
        </el-form-item>
        <el-form-item label="老人ID" prop="elderId">
          <el-input-number v-model="addForm.elderId" :min="1" style="width:100%" />
        </el-form-item>
        <el-form-item label="老人姓名" prop="elderName">
          <el-input v-model="addForm.elderName" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd">提交</el-button>
          <el-button @click="resetAdd">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Check, CircleClose } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'

const router = useRouter()

const screenWidth = ref(window.innerWidth)
const isDesktop = computed(() => screenWidth.value >= 768)
window.addEventListener('resize', () => (screenWidth.value = window.innerWidth))

const tableData = ref([])
const totalItems = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)
const selectedRows = ref([])

const queryParams = reactive({
  name: '',
  mobile: '',
  elderName: '',
  status: ''
})

const statusMap = {
  0: { text: '待确定', type: 'warning' },
  1: { text: '待完成', type: 'primary' },
  2: { text: '取消', type: 'info' },
  3: { text: '过期', type: 'danger' },
  4: { text: '完成', type: 'success' }
}
const statusText = s => statusMap[s]?.text || '未知'
const statusTagType = s => statusMap[s]?.type || 'info'

/* 列表查询 -------------------------------------------------------------- */
const fetchData = async () => {
  loading.value = true
  try {
    const data = await request.get('/visit/admin/visit', {
      params: {
        name: queryParams.name,
        mobile: queryParams.mobile,
        elderName: queryParams.elderName,
        status: queryParams.status || undefined,
        page: currentPage.value,
        size: pageSize.value
      }
    })
    tableData.value = data.records || []
    totalItems.value = data.total || 0
  } catch {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  currentPage.value = 1
  fetchData()
}
const resetQuery = () => {
  Object.assign(queryParams, { name: '', mobile: '', elderName: '', status: '' })
  handleQuery()
}
const handleRefresh = fetchData
const handlePageChange = p => { currentPage.value = p; fetchData() }

/* 新增抽屉 -------------------------------------------------------------- */
const addDrawerVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  userId: 1002,
  name: '',
  mobile: '',
  time: '',
  numberOfPeople: 1,
  elderId: 1003,
  elderName: ''
})
const addRules = {
  userId: [{ required: true, type: 'number', message: '请输入用户ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入预约人姓名', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  time: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  numberOfPeople: [{ required: true, type: 'number', message: '请选择随行人数', trigger: 'change' }],
  elderId: [{ required: true, type: 'number', message: '请输入老人ID', trigger: 'blur' }],
  elderName: [{ required: true, message: '请输入老人姓名', trigger: 'blur' }]
}

const openAddDialog = () => {
  resetAdd()
  addDrawerVisible.value = true
}
const submitAdd = async () => {
  await addFormRef.value.validate()
  try {
    await request.post('/visit/admin/visit', { ...addForm, type: 0 })
    ElMessage.success('新增成功')
    addDrawerVisible.value = false
    fetchData()
  } catch {
    ElMessage.error('新增失败')
  }
}
const resetAdd = () => {
  Object.assign(addForm, {
    userId: 1002,
    name: '',
    mobile: '',
    time: '',
    numberOfPeople: 1,
    elderId: 1003,
    elderName: ''
  })
  nextTick(() => addFormRef.value?.clearValidate())
}

/* 审核 / 取消 / 删除 ---------------------------------------------------- */
const approveVisit = async id => {
  try {
    await ElMessageBox.confirm('确认审核通过该预约？', '提示', { type: 'warning' })
    await request.put(`/visit/admin/visit/${id}/approve`)
    ElMessage.success('审核成功')
    fetchData()
  } catch { }
}
const cancelVisit = async id => {
  try {
    await ElMessageBox.confirm('确认取消该预约？', '提示', { type: 'warning' })
    await request.post(`/visit/admin/visit/${id}/cancel`)
    ElMessage.success('取消成功')
    fetchData()
  } catch { }
}
const deleteRow = async id => {
  try {
    await ElMessageBox.confirm('确定删除该探访预约？', '提示', { type: 'warning' })
    await request.delete(`/visit/admin/visit/${id}`)
    ElMessage.success('删除成功')
    fetchData()
  } catch { }
}
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) return ElMessage.warning('请先选择要删除的预约')
  try {
    await ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条预约？`, '提示', { type: 'warning' })
    await Promise.all(selectedRows.value.map(i => request.delete(`/visit/admin/visit/${i.id}`)))
    ElMessage.success('批量删除成功')
    fetchData()
  } catch { }
}
const handleSelectionChange = val => (selectedRows.value = val)

onMounted(fetchData)
</script>

<style scoped>
.visit-appointment {
  width: 99%;
  height: 84vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 10px;
  background-color: #f5f7fa;
}

.query-section,
.action-section,
.pagination-section {
  flex-shrink: 0;
}

.content-section {
  flex: 1;
  min-height: 0;
  position: relative;
  display: flex;
  flex-direction: column;
}

.query-card {
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  background: linear-gradient(135deg, #ffffff 0%, #fafbff 100%);
}

.query-card .card-header-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.query-card .card-header-title .el-icon {
  margin-right: 8px;
  color: var(--el-color-primary);
}

.query-grid .el-form-item {
  margin-bottom: 16px;
}

.query-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-left: 30px;
}

.action-card,
.content-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.content-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.content-card ::v-deep(.el-card__body) {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  padding: 10px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.total-info {
  font-size: 14px;
  color: #606266;
}

.total-info ::v-deep(.total-count) {
  color: var(--el-color-primary);
  font-size: 16px;
  font-weight: 600;
  margin: 0 4px;
}

.desktop-table,
.mobile-list {
  height: 100%;
  width: 100%;
}

.desktop-table {
  display: flex;
  justify-content: center;
  overflow-x: auto;
  overflow-y: auto;
  max-height: 500px;
}

.mobile-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.mobile-card {
  position: relative;
  margin-bottom: 16px;
  border-radius: 16px;
  background: linear-gradient(145deg, #ffffff 0%, #f7f9fc 100%);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.25s, box-shadow 0.25s;
}

.mobile-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.mobile-card:active {
  transform: scale(0.98);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
}

.card-main {
  padding: 16px 18px 14px 48px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.card-header .left {
  display: flex;
  flex-direction: column;
}

.card-header .name {
  font-size: 17px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
}

.card-header .mobile {
  margin-top: 2px;
  font-size: 13px;
  color: #909399;
}

.card-info {
  margin-bottom: 14px;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  line-height: 22px;
}

.info-item .label {
  color: #606266;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.card-actions .el-button {
  min-width: 60px;
}

@media (max-width: 767px) {
  .mobile-list {
    height: calc(100vh - 220px);
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding: 12px;
  }

  .content-card {
    display: block;
    height: 100%;
  }
}
</style>